<template>
	<view>
		<view>
			<table-title content="门禁卡申请表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor" :isLast="true"></view-item>
			</view>
			<small-title :isNeed="true" content="开卡人员信息"></small-title>
			<view v-if="state==='待申请' || processFlag" style="margin-left: 20rpx;margin-right: 20rpx;">
				<uni-table :newMinWidth="(state==='待申请' || state==='管家已驳回')?300:0" border stripe emptyText="暂无更多数据" >
				    <!-- 表头行 -->
				    <uni-tr>
						<uni-th style="width: 120rpx;" align="center">序号</uni-th>
				        <uni-th style="width: 200rpx;" align="center">姓名</uni-th>
				        <uni-th style="width: 400rpx;" align="center">证件号码</uni-th>
						<uni-th v-if="state==='待申请' || state==='管家已驳回'" style="width: 200rpx;"></uni-th>
				    </uni-tr>
				    <!-- 表格数据行 -->
				    <uni-tr v-for="(item,index) in userList" :key="index">
				        <uni-td align="center">
							{{index + 1}}
						</uni-td>
				        <uni-td>
							<input :disabled="state!=='待申请' && state!=='管家已驳回'" type="text" v-model="item.userName" placeholder="请输入" />
						</uni-td>
				        <uni-td>
							<input :disabled="state!=='待申请' && state!=='管家已驳回'" type="text" v-model="item.idCard" placeholder="请输入18位证件号码" />
						</uni-td>
						<uni-td v-if="state==='待申请' || state==='管家已驳回'">
							<view v-if="state==='待申请' || state==='管家已驳回'">
								<button style="width: 150rpx;margin-left: 0rpx;font-size: 28rpx;" @click="deleteCard(index)">删除</button>
							</view>
						</uni-td>
				    </uni-tr>
				</uni-table>
			</view>
			<button v-if="state==='待申请' || state==='管家已驳回'" class="add-button" @click="addUser()">添加人员+</button>
			
			<view class="cost-all">费用合计：{{allprice}} 元</view>
			<small-title :isNeed="true" :content="state==='待申请' || state==='管家已驳回'?'上传证件资料':'证件资料'"></small-title>
			<access-card-img v-if="state==='待申请' || processFlag" v-for="(item,index) in userList" :firstImg="item.firstImg" 
				:secondImg="item.secondImg" :first="(index+1).toString()" 
				:isChange="state==='待申请' || state==='管家已驳回'" v-on:addImg="addImg"></access-card-img>
			<small-title :isNeed="true" content="支付信息截图"></small-title>
			<!-- <view class="small-title">支付信息截图</view> -->
			<image :class="chargeImg=='/static/uploadImg.png' ? 'pay-image' : 'pay-image-border'" :src="chargeImg" mode="scaleToFill" @tap='chooseImage'></image>
			<small-title content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="state==='待确认'" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="modOrder">收到门禁卡，办结</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="state==='待申请'" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="addOrder">立即申请</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view v-if="state==='管家已驳回'" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="reAddOrder" >重新申请</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
	</view>
</template>

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE,
		syncGetOrder,
	} from "../../..//util/network.js"
	
	import {
		myUploadFile,
		myDownloadFile,
		syncPriceInfo,
	} from "../../..//util/network.js"
	
	import {
		processHistoryList
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				processFlag:false,
				status:-1,
				token:'',
				number: 2,
				recordId: '待分配',
				processNo:'待分配',
				state: '待受理',
				userMsg:{'userName':'','userPhone':'',
					'userCompany':'','userBuilding':''},
				userList1:[
					{'userName':'小明','idCard':'350121200003120117','firstImg':'/static/idCardFirst.png','secondImg':'/static/idCardSecond.png'
					                                                ,'firstImgId':0,'secondImgId':0},
					{'userName':'大明','idCard':'350121200003120117','firstImg':'/static/idCardFirst.png','secondImg':'/static/idCardSecond.png'
					                                                ,'firstImgId':0,'secondImgId':0},
				],                                                                     //开卡人员信息
				userList:[{'userName':'','idCard':'','firstImg':'/static/idCardFirst.png','secondImg':'/static/idCardSecond.png'
				                                               ,'firstImgId':0,'secondImgId':0}],    
				chargeImg:'/static/uploadImg.png',                                     //支付信息截图
				chargeImgId:-1,                                     //支付信息截图
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'制卡完毕','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'收到卡片和票据','time':'2020-03-03 03:33:33'}
				],
				proccessListDefult:[],
				cardPrice: 0,
				allprice: 0,
			}
		},
		methods: {
			/*
			功能：子组件事件触发新增门一行禁卡用户信息
			参数：无
			*/
			addUser(){
				this.userList.push({'userName':'','idCard':'','firstImg':'/static/idCardFirst.png','secondImg':'/static/idCardSecond.png'
				                                               ,'firstImgId':0,'secondImgId':0})
				this.allprice = Math.round(this.userList.length * this.cardPrice * 100)/100
			},
			/*
			功能：子组件事件触发删除对应行的门禁卡用户信息
			参数：
			index：当前门禁卡序号
			*/
			deleteCard(index){
				if(this.userList.length <= 1){
					let temp = {'userName':'','idCard':'','firstImg':'/static/idCardFirst.png','secondImg':'/static/idCardSecond.png'
				                                               ,'firstImgId':0,'secondImgId':0}
					this.$set(this.userList,index,temp)
					this.allprice = this.userList.length * this.cardPrice
					return
				}
				this.userList.splice(index,1)
				this.allprice = Math.round(this.userList.length * this.cardPrice * 100)/100
			},
			
			/*
			功能：子组件事件触发修改对应行的身份证照片信息
			参数：
			index：当前门禁卡序号
			position：身份证正反面参数 1：正面   2：反面
			value：本地图片信息地址
			*/
			addImg(index, position, value, imgId){
				console.log("[info]","调试父子组件通信，我是父组件" + index + "   " + value)
				if(position == 1) {
					this.userList[index].firstImg = value
					this.userList[index].firstImgId = imgId
					console.log(typeof this.userList[index].firstImg)
				}else {
					this.userList[index].secondImg = value
					this.userList[index].secondImgId = imgId
				}
			},
			
			/*
			功能：支付截图点击事件触发修改或预览照片，如果是待申请 则点击修改照片，否则则是预览
			参数：无
			*/
			chooseImage(){
				console.log("ceshi",this.state)
				if(this.state === '待申请' || this.state==='管家已驳回') {
					uni.chooseImage({
						count: 1,
						sourceType: ['album', 'camera'],
						// #ifdef MP-WEIXIN
						sizeType: ['compressed'],
						// #endif
						success: (res) => {
							let a = myUploadFile(this.token, res.tempFilePaths[0])
							 a.then((v)=>{
								 this.chargeImgId = v
								 console.log("zuizhongid",this.chargeImgId)
							})
							this.chargeImg = res.tempFilePaths[0];
						}
					})
				}else{
					uni.previewImage({
						current: 0,
						urls: [this.chargeImg]
					})
				}
			},
			
			async loadImg(chargeFileId){
				// let _this = this
				const res = await uni.downloadFile({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/file/download/` + chargeFileId,
					header: {
						'Authorization': this.token,
					},
				})
				return new Promise((resolve, reject) => {
				        resolve(res[1].tempFilePath)
				})
			},
			
			/*
			功能：工单详细页处理通用函数
			参数：
			option：操作类型（先定成 创建、写入、查询）
			*/
			addOrder(){
				if(this.checkPara() == -1){
					return -1
				}
				console.log("[info]","工单已创建，工单号为：" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/access-card/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						detail: JSON.stringify(this.userList),
						payScreenshotId:this.chargeImgId,
						price:this.allprice,
						commentMsg: '租户发起申请'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					}
				})
			},
			
			checkPara(){
				let flag = 0
				if(this.userList.length == 0){
					uni.showModal({
						content:'请添加人员',
						showCancel:false
					})
					flag = -1
					return flag
				}
				if(this.allprice <= 0){
					uni.showModal({
						content:'未查询到门禁卡单价，请联系楼层管家处理',
						showCancel:false
					})
					flag = -1
					return flag
				}
				for(var i = 0; i < this.userList.length; i++){
					console.log(item)
					this.userList[i].userName = this.userList[i].userName.trim()
					let item = this.userList[i]
					if(item.userName.trim() == ""){
						uni.showModal({
							content:'姓名不能为空',
							showCancel:false
						})
						flag = -1
						break
					}
					if(item.idCard == "" || item.idCard.length != 18 || !(/^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/.test(item.idCard))){
						uni.showModal({
							content:'请输入正确的证件号码',
							showCancel:false
						})
						flag = -1
						break
					}
					if(item.firstImgId == 0 || item.secondImgId == 0){
						uni.showModal({
							content:'请点击选择身份证图片',
							showCancel:false
						})
						flag = -1
						break
					}
					if(this.chargeImgId == -1){
						uni.showModal({
							content:'请点击上传支付截图',
							showCancel:false
						})
						flag = -1
						break
					}
				}
				return flag
			},
			
			modOrder(){
				console.log("[info]","收到门禁卡办结：" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/access-card/finish/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						commentMsg: '租户已确认收到门禁卡办结'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("门禁卡申请办结调用失败")
					}
				})
			},
			getOrder(){
				let a = syncGetOrder("access-card/show/" + this.recordId)
				 a.then((res)=>{
					 console.log("异步",res)
					 if(res.data.code == 200){
						 switch(parseInt(res.data.data.status)) {
						      case 0:
						         this.state = "待管家审核"
						         break;
						      case 1:
						         this.state = "待管家派送"
						         break;
						 	 case 2:
						         this.state = "待确认"
						 	    break;
						 	 case 3:
						         this.state = "已办结"
						 	    break;
						 	 case 4:
						         this.state = "管家已驳回"
						 	    break;
						      default:
						         this.state = "待申请"
						 } 
						 this.userList = JSON.parse(res.data.data.detail)
						 if(this.state == "管家已驳回"){
							 let buildId = uni.getStorageSync('userinfo').buildId
							 let price = syncPriceInfo(0,1,buildId) //查询单价 门禁卡类，楼盘生效类， 所属楼盘
							 price.then((res) => {
							 	console.log("价格",res)
							 	try{
							 		this.cardPrice = res.data.data[0].price
							 	}catch(e){
							 		this.cardPrice = 0
							 	}
							 	this.allprice = this.cardPrice * this.userList.length
							 	if(this.cardPrice == 0){
							 		let priceNew = syncPriceInfo(0,0) //查询单价 门禁卡类，地域类
							 		priceNew.then((res) => {
							 			this.cardPrice = res.data.data[0].price
							 			this.allprice = this.cardPrice * this.userList.length
							 		})
							 	}
							 })
						 }else{
							 this.allprice = res.data.data.price
						 }
						 this.processNo = res.data.data.processNo
						 this.chargeImgId = res.data.data.payScreenshotId
						 this.proccessListDefult=processHistoryList(res.data.data.processDetail)
						 this.processFlag = true
						 let b = this.loadImg(this.chargeImgId)
						 console.log("imgID",this.userList)
						 b.then((v)=>{
						 	this.chargeImg = v
						 })
						 for (var i = 0; i < this.userList.length; i++) {
						 	let index = i
						 	let c = this.loadImg( this.userList[i].firstImgId)
						 	c.then((v)=>{
						 		this.userList[index].firstImg = v
								this.$forceUpdate()
						 	})
						 	let d = this.loadImg(this.userList[i].secondImgId)
						 	d.then((v)=>{
						 		this.userList[index].secondImg = v
								this.$forceUpdate()
						 	})
						 }
					}
				})
			},
			reAddOrder(){
				if(this.checkPara() == -1){
					return -1
				}
				console.log("[info]","重新提交：" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/access-card/mod/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					data: {
						detail: JSON.stringify(this.userList),
						payScreenshotId:this.chargeImgId,
						price:this.allprice,
						commentMsg: '租户重新发起申请'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						if(res.data.code == 200){
							uni.navigateBack()
						}
					},
					fail: (res) => {
						console.log("门禁卡申请重新提交调用失败")
					}
				})
			},
			getCardPrice(){
				console.log("[info]","门禁卡单价查询成功" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/access-card/price`,
					header: {
						'Authorization': this.token,
					},
					method:'GET',
					success: function (res) {
						console.log("查询门禁卡单价成功",res.data);
						this.cardPrice = res.data.cardPrice
					}
				})
			},
			back(){
				uni.navigateBack()
			}
		},
		onLoad(option) {
			//传入单号
			let userInfo = uni.getStorageSync('userinfo')
			if(userInfo != null){
				this.userMsg.userBuilding = userInfo.title
				this.userMsg.userFloor = userInfo.floor
				this.recordId = option.id
				this.state = option.state
				this.token = uni.getStorageSync('token')
				console.log("token测试",this.token)
			}else{
				uni.navigateTo('../../login/login')
			}
		},
		mounted() {
			//如果是新建表单则不查询
			let buildId = uni.getStorageSync('userinfo').buildId
			let price = syncPriceInfo(0,1,buildId) //查询单价 门禁卡类，楼盘生效类， 所属楼盘

			if(this.state != '待申请'){
				this.getOrder()
			}else{
				let price = syncPriceInfo(0,1,buildId) //查询单价 门禁卡类，楼盘生效类， 所属楼盘
				price.then((res) => {
					console.log("价格",res)
					try{
						this.cardPrice = res.data.data[0].price
					}catch(e){
						this.cardPrice = 0
					}
					this.allprice = this.cardPrice
					if(this.cardPrice == 0){
						let priceNew = syncPriceInfo(0,0) //查询单价 门禁卡类，地域类
						priceNew.then((res) => {
							this.cardPrice = res.data.data[0].price
							this.allprice = this.cardPrice
						})
					}
				})
			}
		}
	}
</script>

<style>
/* 	@import "../../../static/css/upload-imgs.css"; */
	page{
		background-color: #F1F1F1
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: flex-end;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.picture-part{
		display: flex;
		margin: 0 0 10rpx 50rpx;
		font-size: 100rpx;
		font-weight: 200;
		align-items: center;
		justify-content: center;	
		width: 150rpx;
		height: 150rpx;
		border: dashed 1rpx #000000;
	}
	.picture-style{
		width: 155rpx;
		height: 155rpx;
		margin: 0 0 10rpx 50rpx;
	}
	.picture-note-access{
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 50rpx;
		font-size: 30rpx;
	}
	.picture-block-access{
		width: 201rpx;
		display: flex;
		flex-direction: column;
	}
	.picture-block{
		display: flex;
		flex-direction: column;
		justify-content: center;
		margin-left: 60rpx;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button[disabled]{
		background-color: #555555;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.picture-list{
		display: flex;
		margin-top: 10rpx;
	}
	.wrong-logo{
		width: 40rpx;
		height: 40rpx;
		margin-bottom: -40rpx;
		margin-left: 165rpx;
		z-index: 999;
		background-color: #555555
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.cost-all{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.small-title{
		margin: 20rpx 0 20rpx 50rpx;
	}
	.pay-image{
		margin: 20rpx 0 20rpx 150rpx;
		width: 130rpx;
		height: 130rpx;
	}
	.pay-image-border{
		border:2rpx solid;
		border-radius: 2px;
		margin: 20rpx 0 20rpx 150rpx;
		width: 126rpx;
		height: 126rpx;
	}
</style>
